﻿using AuSys.Database.Context;
using AuSys.Database.Context.Specific;
using AuSys.Models.Identities;
using AuSys.Repos.Identities;
using AuSys.Services.App.ActionFilters;
using AuSys.Services.App.OpenApi;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace AuSys.Controllers.System
{
    [ApiController]
    [Route("dev/[action]")]
    public class DevController(
        NSwagTsGenService nSwagTsGenService,
        DataContext dataContext,
        UserRepo userRepo)
        : ControllerBase
    {
        [DevOnly]
        public async Task<string> GenApiTsClient()
        {
            var codeLength = await nSwagTsGenService.GenApiTsClient();
            return $"生成成功，长度 {codeLength}";
        }

        [HttpPost]
        [MasterKeyRequired]
        public string InitAdmin(string? userName, string? masterKey)
        {
            _ = masterKey;
            var initialPwd = UserRepo.GetValidRandomPassword();
            var newUser = new UserDto()
            {
                Name = userName,
                Password = initialPwd,
                Type = UserType.Admin
            };
            userRepo.CreateUser(newUser, true);
            return $"创建成功，密码为<{initialPwd}>，立即登录并更改";
        }

        [HttpPost]
        [DevOnly]
        public string InitSqliteTempDb()
        {
            if (dataContext.AcceptDbType != DataSqliteTempContext.dbType)
                return $"配置项Db:Type必须使用{DataSqliteTempContext.dbType}";
            var created = dataContext.Database.EnsureCreated();
            return created ? "创建成功" : "已存在，未创建";
        }

        [HttpPost]
        [DevOnly]
        public string InitEnforceSqliteTempDb()
        {
            if (dataContext.AcceptDbType != DataSqliteTempContext.dbType)
                return $"配置项Db:Type必须使用{DataSqliteTempContext.dbType}";
            dataContext.Database.EnsureDeleted();
            dataContext.Database.EnsureCreated();
            return "创建成功";
        }

        [HttpPost]
        [MasterKeyRequired]
        public string MigrateDb(string? masterKey)
        {
            lock (migrationLock)
            {
                if (dataContext.AcceptDbType == DataSqliteTempContext.dbType)
                    return $"配置项Db:Type不能使用{DataSqliteTempContext.dbType}";
                _ = masterKey;
                dataContext.Database.Migrate();
                return "迁移成功";
            }
        }
        private readonly static Lock migrationLock = new();
    }
}
